package org.qiyu.live.web.starter;

import com.alibaba.cloud.commons.lang.StringUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.qiyu.live.common.interfaces.enums.GatewayHeaderEnum;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * @ClassName: 用户信息拦截器
 * @Description: TODO
 * @Author zhangguangyan
 * @Date 2023/08/31/ 20:15:20
 * @Version 1.0
 */
public class QiyuUserInfoInterceptor implements HandlerInterceptor {
    //所有 web 请求来到这里的时候，都要被拦截
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        //所有web请求来到
        String userIdStr = request.getHeader(GatewayHeaderEnum.USER_LOGIN_ID.getName());
        //可能是走了接口白名单，这里不做取数判断
        if (StringUtils.isEmpty(userIdStr)) {
            return true;
        }
        Long userId = Long.valueOf(userIdStr);
        //把 userId 放入线程本地变量中
        QiyuRequestContext.put(RequestConstants.QIYU_USER_ID, userId);
        return HandlerInterceptor.super.preHandle(request,
                response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        QiyuRequestContext.clear();
        HandlerInterceptor.super.postHandle(request, response,
                handler, modelAndView);
    }
}
